using System;
using System.Linq;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using VSSAHT.Transfer;
using System.Collections.Generic;
using System.Diagnostics;
using VSS_AHT.DataAccess;

namespace VSSAHT.DataAccess
{
	public class RoleDataAccess : RoleDataAccessBase, IRoleDataAccess
	{

        private RoleDTO _searchObject;
        /// <summary>
        /// Search Object Property
        /// </summary>
        public RoleDTO SearchObject
        {
            get
            {
                return _searchObject;
            }
            set
            {
                if (_searchObject != value)
                {
                    _searchObject = value;
                }
            }
        }

        #region Methods

        public IList<RoleDTO> Search()
        {
            IList<RoleDTO> collection = null;
            try
            {
                using (VSSAHTDataContext dataContext = new VSSAHTDataContext(base.ConnectionString))
                {
                    IQueryable<Role> query = dataContext.Roles;
                    if (!String.IsNullOrEmpty(_searchObject.RoleName))
                    {
                        query = query.Where(e => e.RoleName.Contains(_searchObject.RoleName));
                        //hasConditions = true;
                    }


                    collection = new List<RoleDTO>();
                    foreach (var item in query)
                    {
                        collection.Add(RoleMapper.ToBusinessObject(item));
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return collection;
        }
        #endregion
  
        public RoleDTO GetByCode(string code)
        {
            RoleDTO role = null;
            // note: here you can use any persistance library
            // to dynamically populate a list of all objects
            try
            {
                // Process
                using (IDbConnection connection = DbProviderFactory.CreateConnection())
                {
                    connection.ConnectionString = ConnectionString;
                    using (VSSAHTDataContext biocode = new VSSAHTDataContext(connection))
                    {
                        role = RoleMapper.ToBusinessObject(biocode.Roles.Where(x => x.RoleCode == code).SingleOrDefault()); 
                    }
                }
            }
            catch
            {
            }
            return role;
        }
	}
}
